/************************************************************
 * 文件名: sessionfriendarea.cpp
 * 功能描述: 实现会话/好友/申请列表滚动展示区的具体逻辑。
 * 作者: 李强
 * 创建日期: [请填写日期]
 * 修改历史:
 ************************************************************/
#include "sessionfriendarea.h"

#include <QScrollBar>
#include <QVBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <QStyleOption>
#include <QPainter>
#include <QDebug>
#include <QPixmap>
#include <QPainterPath>

#include "model/data.h"

SessionFriendArea::SessionFriendArea(QWidget *parent)
    : QScrollArea(parent)
{
    // 1. 启用滚动区域自适应内容大小
    setWidgetResizable(true);

    // 2. 设置滚动条和整体样式
    verticalScrollBar()->setStyleSheet(
        "QScrollBar:vertical { width: 2px; background-color: rgb(211, 15, 15); }");
    horizontalScrollBar()->setStyleSheet(
        "QScrollBar:horizontal { height: 0px; }");
    setStyleSheet("QWidget { border: none; }");

    // 3. 创建内容容器并设置布局
    container = new QWidget(this);
    setWidget(container);

    QVBoxLayout *layout = new QVBoxLayout(container);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    layout->setAlignment(Qt::AlignTop);

    // 4. 添加临时测试数据（后续可删除）
    QIcon icon(":/recource/image/bjt.jpg");
    for (int i = 0; i < 3; ++i)
    {
        addItem(SessionItemType,
                QString::number(i),
                icon,
                QString("张三%1").arg(i),
                QString("最后一条消息%1").arg(i));
    }
}

void SessionFriendArea::clear()
{
    QLayout *layout = container->layout();
    // 遍历布局管理器中的所有元素，并且依次从布局管理器中删除掉
    for (int i = layout->count() - 1; i >= 0; --i)
    {
        // takeAt 就能移除对应下标的元素
        QLayoutItem *item = layout->takeAt(i);

        // 别忘了，还需要对这个对象进行 "释放"
        if (item->widget())
        {
            // 把这个移除的内容的 widget 进行释放
            // 正常的时候，new 出来的对象添加到布局管理器的。。。
            delete item->widget();
        }
    }
}

void SessionFriendArea::addItem(ItemType itemType, const QString &id, const QIcon &avatar, const QString &name, const QString &text)
{
    qDebug() << "addItem called, name:" << name;
    SessionFriendItem *item = nullptr;
    if (itemType == SessionItemType)
    {
        item = new SessionItem(this, id, avatar, name, text);
    }
    else if (itemType == FriendItemType)
    {
        item = new FriendItem(this, id, avatar, name, text);
    }
    else if (itemType == ApplyItemType)
    {
        item = new ApplyItem(this, id, avatar, name);
    }
    else
    {
        LOG() << "错误的 ItemType! itemType=" << itemType;
        return;
    }
    container->layout()->addWidget(item);
}

void SessionFriendArea::clickItem(int index)
{
    if (index < 0 || index >= container->layout()->count())
    {
        LOG() << "点击元素的下标超出范围！ index=" << index;
        return;
    }
    QLayoutItem *layoutItem = container->layout()->itemAt(index);
    if (layoutItem == nullptr || layoutItem->widget() == nullptr)
    {
        LOG() << "指定的元素不存在! index=" << index;
        return;
    }
    SessionFriendItem *item = dynamic_cast<SessionFriendItem *>(layoutItem->widget());
    item->select();
}

///////////////////////////////////////////////////////
/// 滚动区域中的 Item 的实现
/// ///////////////////////////////////
SessionFriendItem::SessionFriendItem(QWidget *owner, const QIcon &avatar, const QString &name, const QString &text)
    : owner(owner)
{
    this->setFixedHeight(70);
    setAttribute(Qt::WA_TranslucentBackground);
    setStyleSheet("QWidget { background-color: transparent; }");

    // 创建布局管理器
    QGridLayout *layout = new QGridLayout();
    layout->setContentsMargins(0, 0, 0, 0); // 头像贴左
    layout->setHorizontalSpacing(0);
    layout->setVerticalSpacing(0);
    this->setLayout(layout);
    // 创建头像（圆形，贴左）
    QLabel *avatarLabel = new QLabel();
    avatarLabel->setFixedSize(50, 50);
    QPixmap rawPixmap = avatar.pixmap(50, 50);
    QPixmap roundPixmap(50, 50);
    roundPixmap.fill(Qt::transparent);

    QPainter painter(&roundPixmap);
    painter.setRenderHint(QPainter::Antialiasing);
    QPainterPath path;
    path.addEllipse(0, 0, 50, 50);
    painter.setClipPath(path);
    painter.drawPixmap(0, 0, 50, 50, rawPixmap);

    avatarLabel->setPixmap(roundPixmap);
    avatarLabel->setScaledContents(true);
    avatarLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    // 创建名字
    QLabel *nameLabel = new QLabel();
    nameLabel->setText(name);
    nameLabel->setStyleSheet("QLabel { font-size:18px;font-weight:400;color:#000 }");
    nameLabel->setFixedHeight(50);
    nameLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    nameLabel->setContentsMargins(10, 0, 0, 0);
    // 创建消息预览
    messageLabel = new QLabel();
    messageLabel->setText(text);
    messageLabel->setFixedHeight(35);
    messageLabel->setStyleSheet("color :#000");
    messageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    messageLabel->setContentsMargins(10, 0, 0, 0);
    // 头像处于0，0，位置  占据2行 2 列
    layout->addWidget(avatarLabel, 0, 0, 2, 2);
    layout->addWidget(nameLabel, 0, 2, 1, 8);
    layout->addWidget(messageLabel, 1, 2, 1, 8);
}

void SessionFriendItem::paintEvent(QPaintEvent *event)
{
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

void SessionFriendItem::mousePressEvent(QMouseEvent *event)
{
    (void)event;
    select();
}

void SessionFriendItem::enterEvent(QEnterEvent *event)
{
    Q_UNUSED(event);
    if (selected)
        return;
    setStyleSheet("QWidget { background-color: rgb(215, 215, 215); }");
}

void SessionFriendItem::leaveEvent(QEvent *event)
{
    Q_UNUSED(event);
    if (selected)
        return;
    setStyleSheet("QWidget { background-color: transparent; }");
}

void SessionFriendItem::select()
{
    selected = true;
    update(); // 触发重绘

    // 还原兄弟节点
    const QObjectList siblings = parentWidget()->children();
    for (QObject *child : siblings)
    {
        if (!child->isWidgetType() || child == this)
            continue;
        SessionFriendItem *item = qobject_cast<SessionFriendItem *>(child);
        if (item && item->selected)
        {
            item->selected = false;
            item->setStyleSheet("QWidget { background-color: transparent; }");
            item->update();
        }
    }
    active();
}

void SessionFriendItem::active()
{
    // 父类的 active 不需要实现
    //
}

///////////////////////////////////////////////////////
/// 会话 Item 的实现
/// //////////////////////////////////////////////////
SessionItem::SessionItem(QWidget *owner, const QString &chatSessionId, const QIcon &avatar, const QString &name, const QString &lastMessage)
    : SessionFriendItem(owner, avatar, name, lastMessage), chatSessionId(chatSessionId)
{
}

void SessionItem::active()
{
    // TDDO
    LOG() << "点击了SessionItem 触发的逻辑 chatSessionId = " << chatSessionId;
}

///////////////////////////////////////////////////////
/// 好友 Item 的实现
/// //////////////////////////////////////////////////
FriendItem::FriendItem(QWidget *owner, const QString &userId, const QIcon &avatar, const QString &name, const QString &description)
    : SessionFriendItem(owner, avatar, name, description), userId(userId)
{
}

void FriendItem::active()
{
    // TODO
    LOG() << "点击FriendItem 触发的逻辑 userId = " << userId;
}

///////////////////////////////////////////////////////
/// 好友申请 Item 的实现
/// //////////////////////////////////////////////////

ApplyItem::ApplyItem(QWidget *owner, const QString &userId, const QIcon &avatar, const QString &name)
    : SessionFriendItem(owner, avatar, name, ""), userId(userId)
{
    // 1.移除父类的 messageLabel
    QGridLayout *layout = dynamic_cast<QGridLayout *>(this->layout());
    layout->removeWidget(messageLabel);
    // 释放内存，避免内存泄露
    delete messageLabel;

    // 2.创建两个按钮
    QPushButton *acceptBtn = new QPushButton();
    acceptBtn->setText("同意");
    QPushButton *rejectBtn = new QPushButton();
    rejectBtn->setText("拒绝");

    // 3。添加到布局管理器中
    layout->addWidget(acceptBtn, 1, 2, 1, 1);
    layout->addWidget(rejectBtn, 1, 3, 1, 1);
}

void ApplyItem::active()
{
    LOG() << "点击ApplyItem" << "";
}
